package com.ruoyi.hotel.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.http.Header;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hotel.domain.*;
import com.ruoyi.hotel.enums.HotelRoomChangeTypeEnum;
import com.ruoyi.hotel.mapper.*;
import com.ruoyi.hotel.service.IHotelRoomChangeService;
import com.ruoyi.hotel.service.IHotelRoomService;
import com.ruoyi.hotel.util.TimeUtil;
import com.ruoyi.hotel.wx.mp.config.service.WechatTemplateMessageService;
import com.ruoyi.system.domain.SystemNotifyMessage;
import com.ruoyi.system.mapper.SystemNotifyMessageMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import com.ruoyi.hotel.service.IHotelRoomListService;
import org.springframework.web.client.RestTemplate;

/**
 * 酒店房间信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-13
 */
@Service
public class HotelRoomListServiceImpl implements IHotelRoomListService {

    private static Logger logger = LoggerFactory.getLogger(HotelRoomListServiceImpl.class);

    @Autowired
    private HotelRoomListMapper hotelRoomListMapper;

    @Autowired
    private HotelRoomListHistoryMapper hotelRoomListHistoryMapper;

    @Autowired
    private HotelUserMapper hotelUserMapper;

    @Autowired
    private SystemNotifyMessageMapper systemNotifyMessageMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IHotelRoomService hotelRoomService;

    @Autowired
    private IHotelRoomChangeService hotelRoomChangeService;

    @Autowired
    private HotelInfoMapper hotelInfoMapper;

    @Autowired
    private HotelRoomChangeMapper hotelRoomChangeMapper;


    @Autowired
    private WechatTemplateMessageService wechatTemplateMessageService;


    /**
     * 发送每日汇总
     *
     * @return
     */
    public void sendDaySummary() {
        //获取当前日期字符串
        List<HotelUser> hotelUserList = hotelUserMapper.selectHotelUserListGroupByUserId(new HotelUser());
        if (hotelUserList == null || hotelUserList.size() == 0) {
            logger.error("没有待发送每日汇总的用户!!!");
            return;
        }

        //循环遍历
        for (HotelUser hotelUser : hotelUserList) {
            SysUser sysUser = userService.selectUserById(hotelUser.getUserId());
            if (sysUser == null || StringUtils.isBlank(sysUser.getOpenid())) {
                continue;
            }
            this.sendDaySummaryMessage(sysUser.getOpenid(),hotelUser.getHotelGroup());
        }
    }


    /**
     * 酒店房间同步
     *
     * @return 结果
     */
    @Override
    public void rsyncHotelRoomList() {
        //查询酒店列表
        List<HotelInfo> hotelInfoList = hotelInfoMapper.selectHotelInfoList(new HotelInfo());
        if (hotelInfoList == null || hotelInfoList.size() == 0) {
            logger.error("没有待同步的酒店列表!!!");
            return;
        }
        try {
            String checkinDate = TimeUtil.getDateByNumStr(0);
            String checkoutDate = TimeUtil.getDateByNumStr(1);

            //是否在0点-6点之间
            if (TimeUtil.isBelong()) {
                checkinDate = TimeUtil.getDateByNumStr(-1);
                checkoutDate = TimeUtil.getDateByNumStr(0);
            }


            for (int h = 0; h < hotelInfoList.size(); h++) {
                List<HotelRoomList> newHotelRoomList = new ArrayList<>();
                HotelInfo hotelInfo = hotelInfoList.get(h);
                if (hotelInfo.getHotelGroup().equals("yd")) {
//                    newHotelRoomList = this.syncHotelYD(hotelInfo, checkinDate, checkoutDate);
                } else if (hotelInfo.getHotelGroup().equals("jj")) {
                    newHotelRoomList = this.syncHotelJJ(hotelInfo, checkinDate, checkoutDate);
                } else if (hotelInfo.getHotelGroup().equals("hz")) {
                    newHotelRoomList = this.syncHotelHZ(hotelInfo, checkinDate, checkoutDate);
                }


                if (newHotelRoomList.size() > 0) {

                    //更新酒店房间信息 并把设置为本地的roomId进行关联
                    this.insertHotelRoom(newHotelRoomList);

                    //查询出相同酒店 相同用户的酒店房间信息列表
                    List oldHotelRoomList = hotelRoomListMapper.selectHotelRoomListByHotelId(hotelInfo.getHotelId(), "0");

                    List<HotelRoomChange> hotelRoomChanges = new ArrayList<>();
                    //有数据表述不是首次同步
                    if (oldHotelRoomList.size() > 0) {
                        //对比历史数据与新查询到的数据
                        //SysUser sysUser = userService.selectUserById(hotelUser.getUserId());
                        hotelRoomChanges = this.compareHotelRoomList(oldHotelRoomList, newHotelRoomList);
                    }

                    if (hotelRoomChanges.size() > 0) {
                        hotelRoomChangeMapper.batchInsertHotelRoomChange(hotelRoomChanges);
                        List<HotelUser> hotelUserList = hotelUserMapper.selectSyncHotelUserByHotelId(hotelInfo.getHotelId());
                        String isPushMessage = configService.selectConfigByKey("sys.hotel.isPushMessage");
                        for (HotelUser hotelUser : hotelUserList) {
                            SysUser sysUser = userService.selectUserById(hotelUser.getUserId());
                            if (StringUtils.isNotBlank(sysUser.getOpenid()) && isPushMessage.equals("1")) {
                                for (HotelRoomChange sendHotelRoomChange : hotelRoomChanges) {
                                    this.pushMessage(sysUser.getOpenid(), sysUser.getUserId(), sendHotelRoomChange);
                                }
                            }
                        }
                    }

                    //修改之前的数据状态为已处理
//                    hotelRoomListMapper.updateHotelRoomListStatusByTask(hotelUser.getHotelId(),hotelUser.getUserId());

                    //删除之前的数据 下面已经插入了历史数据，所以删除也没关系
                    hotelRoomListMapper.deleteHotelRoomListByHotelId(hotelInfo.getHotelId());

                    //更新新采集到的数据到数据库, 下一次使用这批数据进行对比采集
                    if (newHotelRoomList.size() > 0) {
                        hotelRoomListMapper.batchInsertHotelRoomList(newHotelRoomList);
                        List<HotelRoomListHistory> hotelRoomListHistoryList = JSON.parseArray(JSON.toJSONString(newHotelRoomList), HotelRoomListHistory.class);
                        hotelRoomListHistoryMapper.batchInsertHotelRoomHistoryList(hotelRoomListHistoryList);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过采集到的酒店数据集合筛选出房间
     *
     * @param hotelRoomList
     */
    public void insertHotelRoom(List<HotelRoomList> hotelRoomList) {
        for (HotelRoomList hotelRoomListObj : hotelRoomList) {
            HotelRoom hotelRoom = hotelRoomService.selectHotelRoomByHotelIdAndRoomName(hotelRoomListObj.getHotelId(), hotelRoomListObj.getName());
            if (hotelRoom == null) {
                hotelRoom = new HotelRoom();
                hotelRoom.setHotelId(hotelRoomListObj.getHotelId());
                hotelRoom.setHotelName(hotelRoomListObj.getHotelName());
                hotelRoom.setRoomName(hotelRoomListObj.getName());
                hotelRoom.setPrice(hotelRoomListObj.getPrice());
                hotelRoom.setRoomNum(hotelRoomListObj.getMaxNum());
                hotelRoom.setStatus("0");
                hotelRoom.setHotelGroup(hotelRoomListObj.getHotelGroup());
                hotelRoom.setRoomImage(hotelRoomListObj.getRoomImage());
                hotelRoomService.insertHotelRoom(hotelRoom);
                hotelRoomListObj.setRoomId(hotelRoom.getId());
            } else {
                hotelRoom.setPrice(hotelRoomListObj.getPrice());
                hotelRoom.setRoomNum(hotelRoomListObj.getMaxNum());

                if(!hotelRoom.getStatus().equals(HotelRoomChangeTypeEnum.SOLDOUT.getKey()+"")){
                    hotelRoom.setStatus("0");
                }

                hotelRoom.setRoomImage(hotelRoomListObj.getRoomImage());
                hotelRoomService.updateHotelRoom(hotelRoom);
                hotelRoomListObj.setRoomId(hotelRoom.getId());
            }
        }
    }


    public List<HotelRoomList> syncHotelYD(HotelInfo hotelInfo, String checkinDate, String checkoutDate) {
        List<HotelRoomList> newHotelRoomList = new ArrayList<HotelRoomList>();
        String url = "https://miniapp.yaduo.com/atourlife/miniapp/chain/chainDetailQuote?appVer=3.24.3&version=3.24.3&channelId=60001&deviceId=6533d35a-feb2-49f4-aa04-1fb33da80e7d&platType=7&token=&inactiveId=&clientId=6&elementId=0&traceId=0&activeId=0&activitySource=ydxcx&osversion=Windows%2011%20x64&devbrand=microsoft&devmodel=microsoft&browser=3.3.4&brversion=3.9.9";
        try {
            //使用Restemplate来发送HTTP请求
            RestTemplate restTemplate = new RestTemplate();
            String param = "{\"chainId\":" + hotelInfo.getHotelId() + ",\"checkinDate\":" + "\"" + checkinDate + "\"" + ",\"checkoutDate\":" + "\"" + checkoutDate + "\"" + "}";
            //设置请求header 为 APPLICATION_FORM_URLENCODED
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 请求体，包括请求数据 body 和 请求头 headers
            HttpEntity httpEntity = new HttpEntity(JSONObject.parseObject(param), headers);

            //使用 exchange 发送请求，以String的类型接收返回的数据
            //ps，我请求的数据，其返回是一个json
            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            //logger.info("rsyncHotelRoomList  解析返回的数据: " + strbody.getBody());
            JSONObject jsTemp = JSONObject.parseObject(strbody.getBody());

            int code = jsTemp.getInteger("retcode");
            if (code == 0) {
                JSONObject result = jsTemp.getJSONObject("result");
                JSONObject priceResponse = result.getJSONObject("priceResponse");
                JSONArray chainRoomList = priceResponse.getJSONArray("chainRoomList");
                for (int i = 0; i < chainRoomList.size(); i++) {
                    HotelRoomList hotelRoomList = new HotelRoomList();  //最新采集到的酒店数据集合

                    JSONObject tempJson = chainRoomList.getJSONObject(i);
                    JSONObject roomTypeInfoResponse = tempJson.getJSONObject("roomTypeInfoResponse");
                    JSONObject minRoomPrice = tempJson.getJSONObject("minRoomPrice");

                    JSONArray imageListArr = roomTypeInfoResponse.getJSONArray("imageList");
                    if (imageListArr != null && imageListArr.size() > 0) {
                        hotelRoomList.setRoomImage(imageListArr.getString(0));
                    }

                    hotelRoomList.setHotelId(hotelInfo.getHotelId());
                    hotelRoomList.setHotelName(hotelInfo.getHotelName());
                    hotelRoomList.setHotelGroup(hotelInfo.getHotelGroup());
                    hotelRoomList.setIsHourRoom("0");
                    hotelRoomList.setName(roomTypeInfoResponse.getString("roomTypeName"));
                    hotelRoomList.setCreateTime(new Date());
                    hotelRoomList.setCreateBy("定时任务");
                    hotelRoomList.setUpdateBy("定时任务");
                    hotelRoomList.setStatus("0");
                    hotelRoomList.setUpdateTime(new Date());
                    hotelRoomList.setMaxNum(minRoomPrice.getLong("roomNum"));
                    hotelRoomList.setRoomStatus(roomTypeInfoResponse.getBoolean("isFullRoom") ? "3" : "1");
                    hotelRoomList.setPrice(minRoomPrice.getInteger("price"));
                    hotelRoomList.setOriginPrice(minRoomPrice.getLong("marketPrice").toString());
                    newHotelRoomList.add(hotelRoomList);
                }
            } else {
                this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
            }
        } catch (Exception e) {
            logger.error("YD spider error : " + e.getMessage());
            this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
        }
        return newHotelRoomList;
    }


    public List<HotelRoomList> syncHotelJJ(HotelInfo hotelInfo, String checkinDate, String checkoutDate) {
        List<HotelRoomList> newHotelRoomList = new ArrayList<HotelRoomList>();
        String url = "https://wxapp.bestwehotel.com/gw3/app-mini/trip-goods/hotel/v2/roomRateList";
        //使用Restemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        JSONObject params = new JSONObject();
        params.put("innId", hotelInfo.getHotelId());
        params.put("beginDate", checkinDate);
        params.put("endDate", checkoutDate);
        params.put("days", 1);

        try {
            //设置请求header 为 APPLICATION_FORM_URLENCODED
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("X-WeHotel-Api-Key", "815b9911-41e1-4a22-8b23-cb153333a5d1");
            // 请求体，包括请求数据 body 和 请求头 headers
            HttpEntity httpEntity = new HttpEntity(params, headers);

            //使用 exchange 发送请求，以String的类型接收返回的数据
            //ps，我请求的数据，其返回是一个json
            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            //logger.info("rsyncHotelRoomList  解析返回的数据: " + strbody.getBody());
            JSONObject jsTemp = JSONObject.parseObject(strbody.getBody());
            int code = jsTemp.getInteger("msgCode");
            if (code == 100) {
                //锦江的房间图片是另一个接口 需要重新查询一次
                JSONArray roomTypeList = new JSONArray();
                String hotelInfoUrl = "https://wxapp.bestwehotel.com/gw3/app-mini/trip-search/inn/getHotelInfo";
                RestTemplate hotelInfoRestTemplate = new RestTemplate();
                JSONObject hotelInfoParams = new JSONObject();
                hotelInfoParams.put("innId", hotelInfo.getHotelId());
                httpEntity = new HttpEntity(hotelInfoParams, headers);
                ResponseEntity<String> hotelInfoSrbody = hotelInfoRestTemplate.exchange(hotelInfoUrl, HttpMethod.POST, httpEntity, String.class);
                JSONObject hotelInfoJSONTemp = JSONObject.parseObject(hotelInfoSrbody.getBody());
                if (hotelInfoJSONTemp.getInteger("msgCode") == 100) {
                    JSONObject hotelInfoResult = hotelInfoJSONTemp.getJSONObject("result");
                    roomTypeList = hotelInfoResult.getJSONArray("roomTypeList");
                }

                JSONObject result = jsTemp.getJSONObject("result");
                JSONArray roomRate = result.getJSONArray("roomRate");
                for (int i = 0; i < roomRate.size(); i++) {
                    HotelRoomList hotelRoomList = new HotelRoomList();  //最新采集到的酒店数据集合
                    JSONObject tempJson = roomRate.getJSONObject(i);
                    String roomTypeId = tempJson.getString("roomTypeId");

                    for (int j = 0; j < roomTypeList.size(); j++) {
                        JSONObject roomType = roomTypeList.getJSONObject(j);
                        if (roomType.getString("roomTypeId").equals(roomTypeId)) {
                            JSONArray imageListArr = roomType.getJSONArray("images");
                            if (imageListArr.size() > 0) {
                                hotelRoomList.setRoomImage(imageListArr.getJSONObject(0).getString("imageUrl"));
                            }
                            break;
                        }
                    }

                    hotelRoomList.setHotelId(hotelInfo.getHotelId());
                    hotelRoomList.setHotelName(hotelInfo.getHotelName());
                    hotelRoomList.setHotelGroup(hotelInfo.getHotelGroup());
                    hotelRoomList.setIsHourRoom("0");
                    hotelRoomList.setName(tempJson.getString("roomTypeName"));
                    hotelRoomList.setCreateTime(new Date());
                    hotelRoomList.setCreateBy("定时任务");
                    hotelRoomList.setUpdateBy("定时任务");
                    hotelRoomList.setStatus("0");
                    hotelRoomList.setUpdateTime(new Date());
                    hotelRoomList.setRoomStatus(tempJson.getInteger("quota") == 0 ? "3" : "1");
                    hotelRoomList.setMaxNum(tempJson.getLong("quota"));
                    hotelRoomList.setPrice(tempJson.getInteger("lowestRate"));
                    hotelRoomList.setOriginPrice(tempJson.getString("originalRate"));
//                    if (StringUtils.isNotBlank(hotelRoomList.getRoomImage())) {
//                        hotelRoomList.setRoomImage(hotelRoomList.getRoomImage().substring(0, hotelRoomList.getRoomImage().lastIndexOf("/")));
//                    }
                    newHotelRoomList.add(hotelRoomList);
                }
            }
            //锦江酒店特殊，存在下架酒店返回错误代码，并查询不到所有信息的情况
            else if(code == 411) {
                this.sendHotelErrorMsg(1L, hotelInfo.getHotelName());
            }
            else {
                this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
            }

        } catch (Exception e) {
            logger.error("JJ spider error : " + e.getMessage());
            this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
        }
        return newHotelRoomList;
    }


    public List<HotelRoomList> syncHotelHZ(HotelInfo hotelInfo, String checkinDate, String checkoutDate) {
        List<HotelRoomList> newHotelRoomList = new ArrayList<HotelRoomList>();
        String url = "https://hweb-hotel.huazhu.com/hotels/hotelDetail/getRoomInfo";
        //使用Restemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        JSONObject params = new JSONObject();
        params.put("hotelId", hotelInfo.getHotelId());
        params.put("checkInDate", checkinDate);
        params.put("checkOutDate", checkoutDate);
        params.put("roomCount", 1);
        params.put("guestPerRoom", 1);

        try {
            String resultBody = cn.hutool.http.HttpRequest.post(url)
                    .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b11) XWEB/9129")//头信息，多个头信息多次调用此方法即可
                    .header("sId","cccf5f3552554bd392690b751576aeb2096738235")
                    .header(Header.CONTENT_TYPE,"application/json")
                    .body(params.toJSONString())
                    .timeout(5000)//超时，毫秒
                    .execute().body();

            //设置请求header 为 APPLICATION_FORM_URLENCODED
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
            // 请求体，包括请求数据 body 和 请求头 headers
//            HttpEntity httpEntity = new HttpEntity(params, headers);

            //使用 exchange 发送请求，以String的类型接收返回的数据
            //ps，我请求的数据，其返回是一个json
//            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            //logger.info("rsyncHotelRoomList  解析返回的数据: " + strbody.getBody());
            JSONObject jsTemp = JSONObject.parseObject(resultBody);
            int code = jsTemp.getInteger("code");
            if (code == 200) {
                JSONObject result = jsTemp.getJSONObject("content");
                JSONArray rooms = result.getJSONArray("rooms");
                for (int i = 0; i < rooms.size(); i++) {
                    HotelRoomList hotelRoomList = new HotelRoomList();  //最新采集到的酒店数据集合
                    JSONObject tempJson = rooms.getJSONObject(i);
                    JSONArray activitiesArr = tempJson.getJSONArray("activities");
                    Long stock = 0L;
                    if (activitiesArr.size() > 0) {
                        for (int j = 0; j < activitiesArr.size(); j++) {
                            JSONObject activities = activitiesArr.getJSONObject(j);
                            if (activities.getString("name").equals("星会员价")) {
                                stock = activities.getLong("stock");
                                break;
                            }
                        }
                    }
                    hotelRoomList.setHotelId(hotelInfo.getHotelId());
                    hotelRoomList.setHotelName(hotelInfo.getHotelName());
                    hotelRoomList.setHotelGroup(hotelInfo.getHotelGroup());
                    hotelRoomList.setIsHourRoom("0");
                    hotelRoomList.setName(tempJson.getString("name"));
                    hotelRoomList.setRoomImage(tempJson.getString("photo"));
                    hotelRoomList.setCreateTime(new Date());
                    hotelRoomList.setCreateBy("定时任务");
                    hotelRoomList.setUpdateBy("定时任务");
                    hotelRoomList.setStatus("0");
                    hotelRoomList.setMaxNum(stock);
                    hotelRoomList.setUpdateTime(new Date());
                    hotelRoomList.setRoomStatus(tempJson.getString("stockType").equals("3") ? "3" : "1");
                    hotelRoomList.setPrice(tempJson.getInteger("lowestPrice"));
                    hotelRoomList.setOriginPrice(tempJson.getLong("lowestMarketPrice").toString());
                    newHotelRoomList.add(hotelRoomList);
                }
            } else {
                this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
            }

        } catch (Exception e) {
            logger.error("HZ spider error : " + e.getMessage());
            this.sendRoomListErrorMsg(1L, hotelInfo.getHotelName());
        }
        return newHotelRoomList;
    }


    /**
     * 对比历史酒店房间数据与新采集到的酒店房间数据的每条数据进行业务处理
     *
     * @return 结果
     */
    public List<HotelRoomChange> compareHotelRoomList(List<HotelRoomList> oldHotelRoomList, List<HotelRoomList> newHotelRoomList) {
        List<HotelRoomChange> hotelRoomChanges = new ArrayList<>();

        //判断价格是否变动 房间状态是否变动
        for (int i = 0; i < oldHotelRoomList.size(); i++) {
            HotelRoomList oldHotelRoom = oldHotelRoomList.get(i);
            for (int j = 0; j < newHotelRoomList.size(); j++) {
                HotelRoomList newHotelRoom = newHotelRoomList.get(j);
                if (oldHotelRoom.getName().equals(newHotelRoom.getName())) {
                    //判断价格
                    if (oldHotelRoom.getPrice().longValue() != newHotelRoom.getPrice().longValue()) {
                        //金额变动 推送通知
                        if (oldHotelRoom.getPrice().longValue() > newHotelRoom.getPrice().longValue()) {
                            //降价

                            HotelRoomChange hotelRoomChange = new HotelRoomChange();
                            hotelRoomChange.setHotelId(newHotelRoom.getHotelId());
                            hotelRoomChange.setHotelGroup(newHotelRoom.getHotelGroup());
                            hotelRoomChange.setHotelName(newHotelRoom.getHotelName());
                            hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.REDUCE.getKey());
                            hotelRoomChange.setRoomId(newHotelRoom.getRoomId());
                            hotelRoomChange.setRoomName(newHotelRoom.getName());
                            hotelRoomChange.setPrice(newHotelRoom.getPrice());
                            hotelRoomChange.setBeforePrice(oldHotelRoom.getPrice());
                            hotelRoomChange.setChangePrice(newHotelRoom.getPrice().intValue() - oldHotelRoom.getPrice().intValue());
                            hotelRoomChanges.add(hotelRoomChange);

                            HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(newHotelRoom.getRoomId());
                            hotelRoom.setStatus(HotelRoomChangeTypeEnum.REDUCE.getKey() + "");
                            hotelRoomService.updateHotelRoom(hotelRoom);

                            //this.pushMessage(HotelRoomChangeTypeEnum.REDUCE.getKey(),oldHotelRoom,newHotelRoom,sysUser);
                        } else {
                            //涨价
                            HotelRoomChange hotelRoomChange = new HotelRoomChange();
                            hotelRoomChange.setHotelId(newHotelRoom.getHotelId());
                            hotelRoomChange.setHotelGroup(newHotelRoom.getHotelGroup());
                            hotelRoomChange.setHotelName(newHotelRoom.getHotelName());
                            hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.INCREASE.getKey());
                            hotelRoomChange.setRoomId(newHotelRoom.getRoomId());
                            hotelRoomChange.setRoomName(newHotelRoom.getName());
                            hotelRoomChange.setPrice(newHotelRoom.getPrice());
                            hotelRoomChange.setBeforePrice(oldHotelRoom.getPrice());
                            hotelRoomChange.setChangePrice(newHotelRoom.getPrice().intValue() - oldHotelRoom.getPrice().intValue());
                            hotelRoomChanges.add(hotelRoomChange);

                            HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(newHotelRoom.getRoomId());
                            hotelRoom.setStatus(HotelRoomChangeTypeEnum.INCREASE.getKey() + "");
                            hotelRoomService.updateHotelRoom(hotelRoom);

                            //this.pushMessage(HotelRoomChangeTypeEnum.INCREASE.getKey(),oldHotelRoom,newHotelRoom,sysUser);
                        }
                    }
                    //判断房间状态
                    if (!oldHotelRoom.getRoomStatus().equals(newHotelRoom.getRoomStatus())) {
                        //状态变动 推送通知
                        if (newHotelRoom.getRoomStatus().equals("1") && oldHotelRoom.getRoomStatus().equals("3")) {
                            //补充了房间
                            HotelRoomChange hotelRoomChange = new HotelRoomChange();
                            hotelRoomChange.setHotelId(newHotelRoom.getHotelId());
                            hotelRoomChange.setHotelGroup(newHotelRoom.getHotelGroup());
                            hotelRoomChange.setHotelName(newHotelRoom.getHotelName());
                            hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.SUPPLEMENT.getKey());
                            hotelRoomChange.setRoomId(newHotelRoom.getRoomId());
                            hotelRoomChange.setRoomName(newHotelRoom.getName());
                            hotelRoomChange.setPrice(newHotelRoom.getPrice());
                            hotelRoomChange.setBeforePrice(oldHotelRoom.getPrice());
                            hotelRoomChange.setChangePrice(newHotelRoom.getPrice().intValue() - oldHotelRoom.getPrice().intValue());
                            hotelRoomChanges.add(hotelRoomChange);

                            HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(newHotelRoom.getRoomId());
                            hotelRoom.setStatus(HotelRoomChangeTypeEnum.SUPPLEMENT.getKey() + "");
                            hotelRoomService.updateHotelRoom(hotelRoom);

                            //this.pushMessage(HotelRoomChangeTypeEnum.SUPPLEMENT.getKey(), oldHotelRoom,newHotelRoom,sysUser);
                        } else {
                            //房间订光了
                            HotelRoomChange hotelRoomChange = new HotelRoomChange();
                            hotelRoomChange.setHotelId(newHotelRoom.getHotelId());
                            hotelRoomChange.setHotelGroup(newHotelRoom.getHotelGroup());
                            hotelRoomChange.setHotelName(newHotelRoom.getHotelName());
                            hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.SOLDOUT.getKey());
                            hotelRoomChange.setRoomId(newHotelRoom.getRoomId());
                            hotelRoomChange.setRoomName(newHotelRoom.getName());
                            hotelRoomChange.setPrice(newHotelRoom.getPrice());
                            hotelRoomChange.setBeforePrice(oldHotelRoom.getPrice());
                            hotelRoomChange.setChangePrice(newHotelRoom.getPrice().intValue() - oldHotelRoom.getPrice().intValue());
                            hotelRoomChanges.add(hotelRoomChange);

                            HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(newHotelRoom.getRoomId());
                            hotelRoom.setStatus(HotelRoomChangeTypeEnum.SOLDOUT.getKey() + "");
                            hotelRoomService.updateHotelRoom(hotelRoom);

                            //this.pushMessage(HotelRoomChangeTypeEnum.SOLDOUT.getKey(), oldHotelRoom,newHotelRoom,sysUser);
                        }
                    }
                    break;
                }
            }
        }

        Map<String, HotelRoomList> oldHotelRoomListMap = convertListAfterJava82(oldHotelRoomList);
        Map<String, HotelRoomList> newHotelRoomListMap = convertListAfterJava82(newHotelRoomList);

        for (String key : oldHotelRoomListMap.keySet()) {
            if (!newHotelRoomListMap.containsKey(key)) {
                HotelRoomChange hotelRoomChange = new HotelRoomChange();
                hotelRoomChange.setHotelId(oldHotelRoomListMap.get(key).getHotelId());
                hotelRoomChange.setHotelGroup(oldHotelRoomListMap.get(key).getHotelGroup());
                hotelRoomChange.setHotelName(oldHotelRoomListMap.get(key).getHotelName());
                hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.PULLSHELVES.getKey());
                hotelRoomChange.setRoomId(oldHotelRoomListMap.get(key).getRoomId());
                hotelRoomChange.setRoomName(oldHotelRoomListMap.get(key).getName());
                hotelRoomChange.setPrice(oldHotelRoomListMap.get(key).getPrice());
                hotelRoomChange.setBeforePrice(0);
                hotelRoomChange.setChangePrice(0);
                hotelRoomChanges.add(hotelRoomChange);

                HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(oldHotelRoomListMap.get(key).getRoomId());
                hotelRoom.setStatus(HotelRoomChangeTypeEnum.PULLSHELVES.getKey() + "");
                hotelRoomService.updateHotelRoom(hotelRoom);
                //下架了房间
                //this.pushMessage(HotelRoomChangeTypeEnum.PULLSHELVES.getKey(), oldHotelRoomListMap.get(key),newHotelRoomListMap.get(key),sysUser);
            }
        }

        for (String key : newHotelRoomListMap.keySet()) {
            if (!oldHotelRoomListMap.containsKey(key)) {
                //上新房
                HotelRoomChange hotelRoomChange = new HotelRoomChange();
                hotelRoomChange.setHotelId(newHotelRoomListMap.get(key).getHotelId());
                hotelRoomChange.setHotelGroup(newHotelRoomListMap.get(key).getHotelGroup());
                hotelRoomChange.setHotelName(newHotelRoomListMap.get(key).getHotelName());
                hotelRoomChange.setChangeType(HotelRoomChangeTypeEnum.PUTSHELVES.getKey());
                hotelRoomChange.setRoomId(newHotelRoomListMap.get(key).getRoomId());
                hotelRoomChange.setRoomName(newHotelRoomListMap.get(key).getName());
                hotelRoomChange.setPrice(newHotelRoomListMap.get(key).getPrice());
                hotelRoomChange.setBeforePrice(0);
                hotelRoomChange.setChangePrice(0);
                hotelRoomChanges.add(hotelRoomChange);

                HotelRoom hotelRoom = hotelRoomService.selectHotelRoomById(newHotelRoomListMap.get(key).getRoomId());
                hotelRoom.setStatus(HotelRoomChangeTypeEnum.PUTSHELVES.getKey() + "");
                hotelRoomService.updateHotelRoom(hotelRoom);
                //this.pushMessage(HotelRoomChangeTypeEnum.PUTSHELVES.getKey(), oldHotelRoomListMap.get(key),newHotelRoomListMap.get(key),sysUser);
            }
        }

        return hotelRoomChanges;
    }


    public Map<String, HotelRoomList> convertListAfterJava82(List<HotelRoomList> list) {
        Map<String, HotelRoomList> map = list.stream()
                .collect(Collectors.toMap(HotelRoomList::getName, Function.identity(), (oldData, newData) -> newData));
        return map;
    }


    public void pushMessage(String openId, Long userId, HotelRoomChange hotelRoomChange) {
        int type = hotelRoomChange.getChangeType();
        String pushMessage = "";
        String pushTypeStr = "";
        String pushContent = "";
        String messageRemark = "";
        //SimpleDateFormat sdf = new SimpleDateFormat();
        //sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
        //Date date = new Date();
        //String timeNow = sdf.format(date);
        String timeNow = DateUtils.getTime();
        //降价
        if (type == HotelRoomChangeTypeEnum.REDUCE.getKey()) {
            long price = hotelRoomChange.getBeforePrice().longValue() - hotelRoomChange.getPrice().longValue();
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + " [" + hotelRoomChange.getRoomName() + "] 降价了" + price + "元,现价" + hotelRoomChange.getPrice() + "元";
            messageRemark = "降价时间：" + timeNow;
            pushTypeStr = "降价提醒";
            pushContent = "降价了" + price + "元,现价" + hotelRoomChange.getPrice() + "元,时间：" + timeNow;
        }
        //涨价
        else if (type == HotelRoomChangeTypeEnum.INCREASE.getKey()) {
            long price = hotelRoomChange.getPrice().longValue() - hotelRoomChange.getBeforePrice().longValue();
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + " [" + hotelRoomChange.getRoomName() + "] 涨价了" + price + "元,现价" + hotelRoomChange.getPrice() + "元";
            pushTypeStr = "涨价提醒";
            messageRemark = "涨价时间：" + timeNow;
            pushContent = "涨价了" + price + "元,现价" + hotelRoomChange.getPrice() + "元,时间：" + timeNow;
        }
        //补充了房间
        else if (type == HotelRoomChangeTypeEnum.SUPPLEMENT.getKey()) {
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + " [" + hotelRoomChange.getRoomName() + "] 有房了,现价" + hotelRoomChange.getPrice() + "元";
            pushTypeStr = "有房提醒";
            messageRemark = "有房时间：" + timeNow;
            pushContent = "有房了,现价" + hotelRoomChange.getPrice() + "元,时间：" + timeNow;
        }
        //房间订光了
        else if (type == HotelRoomChangeTypeEnum.SOLDOUT.getKey()) {
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + " [" + hotelRoomChange.getRoomName() + "] 满房了";
            pushTypeStr = "满房提醒";
            messageRemark = "满房时间：" + timeNow;
            pushContent = "满房了,时间：" + timeNow;
        }
        ////下架了房间
        else if (type == HotelRoomChangeTypeEnum.PULLSHELVES.getKey()) {
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + "下架了 [" + hotelRoomChange.getRoomName() + "] 房型";
            pushTypeStr = "下架提醒";
            messageRemark = "下架时间：" + timeNow;
            pushContent = "房型下架了,时间：" + timeNow;
        }
        //上新房
        else if (type == HotelRoomChangeTypeEnum.PUTSHELVES.getKey()) {
            pushMessage = hotelRoomChange.getHotelName() + " " + timeNow + "新上架了 [" + hotelRoomChange.getRoomName() + "] 房型 现价" + hotelRoomChange.getPrice() + "元";
            pushTypeStr = "上架提醒";
            messageRemark = "上架时间：" + timeNow;
            pushContent = "新房型上架了,现价" + hotelRoomChange.getPrice() + "元,时间：" + timeNow;
        }

        SystemNotifyMessage systemNotifyMessage = new SystemNotifyMessage();
        systemNotifyMessage.setTemplateNickname("系统消息");
        systemNotifyMessage.setTemplateContent(pushMessage);
        systemNotifyMessage.setReadStatus(0);
        systemNotifyMessage.setTemplateCode(type + "");
        systemNotifyMessage.setTemplateParams(pushTypeStr);
        systemNotifyMessage.setDeleted(0);
        systemNotifyMessage.setDeleted(0);
        systemNotifyMessage.setIsPush(0);
        systemNotifyMessage.setUserId(userId);
        systemNotifyMessage.setCreateTime(new Date());
        systemNotifyMessage.setTemplateType(2L);
        systemNotifyMessage.setHotelId(hotelRoomChange.getHotelId());
        systemNotifyMessage.setRoomId(hotelRoomChange.getRoomId());

        systemNotifyMessageMapper.createNotifyMessage(systemNotifyMessage);
        String url="https://h5.zhuojing.cc/#/pages/hotel/change/index?hotelId="+hotelRoomChange.getHotelId()+"&roomId="+hotelRoomChange.getRoomId();

        this.sendHotelTemplateMsg(openId, hotelRoomChange.getHotelName(), hotelRoomChange.getHotelName(), hotelRoomChange.getRoomName(), pushContent, messageRemark,url);
    }

    public void sendHotelTemplateMsg(String userOpenid,
                                     String hotelName,
                                     String roomName,
                                     String typeText,
                                     String text,
                                     String remark,
                                     String url
    ) {
        String OrderMsgTemplateId = "YCiTqjl4Q_t4pe09iK3Lm5aDZ17x3O-nWjnc6faxTK0";
        try {
            wechatTemplateMessageService.sendMsg(userOpenid, OrderMsgTemplateId, hotelName, roomName, typeText, text, remark,url);
        } catch (Exception e) {
            logger.error("推送失败：" + e.getMessage());
            System.out.println("推送失败：" + e.getMessage());
        }
    }


    public void sendHotelErrorMsg(Long userId, String hotelName) {
        String tepmplateId = "lkrpK2xvMoJ1acFJOBeLUDk3u4E2XIHz9gs1PgGoUb4";
        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser != null && !StringUtils.isEmpty(sysUser.getOpenid())) {
            String keyword1 = "酒店暂不可定提醒";
            String keyword2 = "[" + hotelName + "]采集失败，请及时查看程序运行是否正常";
            try {
                wechatTemplateMessageService.sendMsg(sysUser.getOpenid(), tepmplateId, "", keyword1, keyword2, "", "","");
            } catch (Exception e) {
                logger.error("推送失败：" + e.getMessage());
                System.out.println("推送失败：" + e.getMessage());
            }
        }
    }

    public void sendRoomListErrorMsg(Long userId, String hotelName) {
        String tepmplateId = "lkrpK2xvMoJ1acFJOBeLUDk3u4E2XIHz9gs1PgGoUb4";

        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser != null && !StringUtils.isEmpty(sysUser.getOpenid())) {
            String keyword1 = "酒店采集失败提醒";
            String keyword2 = "[" + hotelName + "]采集失败，请及时查看程序运行是否正常";
            try {
                wechatTemplateMessageService.sendMsg(sysUser.getOpenid(), tepmplateId, "", keyword1, keyword2, "", "","");
            } catch (Exception e) {
                logger.error("推送失败：" + e.getMessage());
                System.out.println("推送失败：" + e.getMessage());
            }
        }
    }

    public void sendDaySummaryMessage(String openId, String hotelName) {
            String tepmplateId = "-PJUnlUnWclEy5lFEO0EdXY0qL8vsxfJV7x66revzcE";
            String keyword1 = "每日酒店汇总报告";
            String keyword2 = "您关注的所有酒店每日酒店汇总报告已生成";
            String remark = "点击详情立刻查看";
            String url = "https://h5.zhuojing.cc/#/";
            try {
                wechatTemplateMessageService.sendMsg(openId, tepmplateId, "", keyword1, keyword2, "", remark,url);
            } catch (Exception e) {
                logger.error("推送失败：" + e.getMessage());
                System.out.println("推送失败：" + e.getMessage());
            }
    }

    public static void main(String[] args) {
        int i = 1;
        String j = "0";
        System.out.println(j.equals(i+""));
    }
}
